<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function createProxy(target) {
      return new Proxy(target, {
        get(target, key, receiver) {
          console.log(target)
          console.log(key)
          console.log(receiver)
        },
        set(target, key, newValue, receiver) {

        }
      })
    }

    let proxyObj = createProxy({
      fqm: 'fqmyysjjd'
    })

    proxyObj.fqm


    let arr = createArr([1, 2, 3])

    function createArr(target) {
      return new Proxy(target, {
        get(target, key, receiver) {
          // console.log(typeof key) 
          key = Number(key)
          return key < 0 ? target[key + target.length] : target[key]
        },
        set(target, key, value, receiver) {
          // console.log(key) 
          key = Number(key)
          key < 0 ? key = key + length : key
          target.key = value
        }
      })
    }

    console.log(arr[-1])
    // 负值超过长度
    console.log(arr[-5])


    let arr_ = createArr_([1, 2, 3])

    console.log(arr_)
    // 递归
    console.log(arr_[-156])

    function createArr_(target) {
      return new Proxy(target, {
        // 第三个参数可选
        get(target, key, receiver) {
          // console.log(typeof key) 
          key = Number(key)
          if (!Number.isNaN(key)) {
            if (key < 0) {
              // 递归
              return this.get(target, key + target.length, receiver)
            }
            else {
              console.log(target[key])
              return target[key]
            }
          }
          else {
            console.warn('Key is not a number!')
          }
        },
        set(target, key, value, receiver) {
          key = Number(key)
          if (!Number.isNaN(key)) {
            key = Number(key)
            if (key < 0) {
              set(target, key + target.length, receiver)
            }
            else {
              target.key = value
            }
          }
          else {
            console.warn('Key is not a number!')
          }
        }
      })
    }


    var obj = {fqm: 'fqmyysjjd'}
    function fun(obj){
      console.log(obj.fqm)
    }
    // Reflect的方法和Proxy传入的第二个参数的对象Handler的属性方法是一样的
    // 见https://www.cnblogs.com/WindrunnerMax/p/14030532.html
    Reflect.apply(fun, this, [obj])

  </script>
</body>

</html>